const BaseURL = 'http://127.0.0.1:3001';
function request(obj) {
  // 设置默认参数
  let option = {
    method: 'GET',
    url: '',
    async: true,
    data: {},
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    success: function () {},
    error: function () {},
  };
  option = { ...option, ...obj };

  //格式化data参数,将接收参数从{key:value}转为&key=value格式
  let params = [];
  for (const key in option.data) {
    params.push(`${key}=${option.data[key]}`);
  }
  params = params.join('&');

  // 创建http请求对象
  const xhr = new XMLHttpRequest();
  //初始化方法,地址
  option.method.toUpperCase() == 'GET' ||
    ('DELETE' && (option.url += `?${params}`));
  //打开服务器连接
  xhr.open(option.method, BaseURL + option.url, option.async);
  //判断请求方法,发送请求
  if (option.method.toUpperCase() == 'POST' || 'PUT') {
    let ContentType = option.headers['Content-Type'];
    xhr.setRequestHeader('Content-Type', ContentType);
    xhr.send(params);
  } else if (option.method.toUpperCase() == 'GET' || 'DELETE') {
    xhr.send();
  }
  //添加事件监听服务器响应
  xhr.onload = function () {
    option.success(JSON.parse(xhr.responseText));
  };
}
